#!/usr/bin/env python
# -*- coding: utf_8 -*-
# $Id$
import urllib
import urllib2
import htmllib
import formatter
import HTMLParser
import sys

CONST_TRANS_URL = 'http://google.com/translate_t'

g_opener = urllib2.build_opener()
BUFSIZE = 8192

class TransParser(HTMLParser.HTMLParser):
	def __init__(self):
		HTMLParser.HTMLParser.__init__(self)
		self.__isfound = False
		self.__tagname = 'div'
		self.__tagattr = ['id', 'result_box']
		self.result = ''
		
	def handle_starttag(self, tag, attributes):
		if tag == self.__tagname: 
			for name, value in attributes:
				if name == self.__tagattr[0] and value == self.__tagattr[1]:
					self.__isfound = True
	
	def handle_endtag(self, tag):
		if (tag == self.__tagname) and (self.__isfound):
			self.__isfound = False
	
	def handle_data(self, data):
		if (self.__isfound):
			print str(data)
			self.result = str(data)
	
g_parser = TransParser()

def build_trans_url(text='', lang_from='zh_cn', lang_to='en'):
	text = urllib.quote_plus(text)
	return CONST_TRANS_URL + text + '&langpair=' + lang_from + '%7C' + lang_to

def build_post_data(text, lang_from='zh_cn', lang_to='en'):
	post_data='hl=en&ie=UTF8&text='
	post_data += urllib.quote_plus(text)
	post_data += '&langpair='+lang_from+'%7C'+lang_to
	return post_data

def get_cookie():
	resp = g_opener.open(CONST_TRANS_URL)
	cookie = resp.info.get('Cookie', '')
	#print cookie
	return cookie

def get_translate_result(resp):
	while True:
		data = resp.read(BUFSIZE)
		if not data: break
		g_parser.feed(data)
	g_parser.close()
	return g_parser.result

def do_translate(text='', lang_from='zh_cn', lang_to='en'):
	post_data = build_post_data(text, lang_from, lang_to)
	#print post_data
	req = urllib2.Request(url=CONST_TRANS_URL, data=post_data)
	req.add_header('Content-Type', 'application/x-www-form-urlencoded')
	req.add_header('User-Agent', 'Mozilla/5.0')
	req.add_header('Referer', CONST_TRANS_URL)
	resp = g_opener.open(req)
	#print resp.read()
	ret = get_translate_result(resp)
	resp.close()
	return ret

if __name__ == '__main__':

	do_translate(sys.argv[1])
